package com.lujianfei.productprice.ui.cart;

import android.content.DialogInterface;
import android.view.View;

import java.util.List;

import androidx.appcompat.app.AlertDialog;

public class CartPresenter implements CartContract.Presenter {
    CartContract.View view;
    CartContract.Model model;

    public CartPresenter(CartContract.View view) {
        this.view = view;
        this.model = new CartModel();
    }

    @Override
    public void loadData() {
        List<CartEntity> cartEntities = model.loadData();
        view.setData(cartEntities);

        double totalPrice = model.getTotalPrice();
        view.setTotalPrice(totalPrice);
    }

    @Override
    public void addQuantity(CartEntity data) {
        model.addQuantity(data);
        List<CartEntity> cartEntities = model.getData();
        view.setData(cartEntities);

        double totalPrice = model.getTotalPrice();
        view.setTotalPrice(totalPrice);
    }

    @Override
    public void minusQuantity(CartEntity data) {
        model.minusQuantity(data);
        List<CartEntity> cartEntities = model.getData();
        view.setData(cartEntities);

        double totalPrice = model.getTotalPrice();
        view.setTotalPrice(totalPrice);
    }

    @Override
    public boolean submit() {
        boolean submit = model.submit();
        if (submit) {
            model.clearCart();
        }
        return submit;
    }

    @Override
    public void showLongClickDialog(final CartEntity cartEntity) {
        final CharSequence[] items = new CharSequence[]{"删除","取消"};
        new AlertDialog.Builder(view.getContext()).setTitle("提示").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                CharSequence item = items[which];
                if ("删除".equalsIgnoreCase(""+item)){
                    confirmDialog(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            model.delete(cartEntity);
                            loadData();
                        }
                    });
                }
            }
        }).show();
    }

    private void confirmDialog(final View.OnClickListener onOkListener){
        new AlertDialog.Builder(view.getContext()).setTitle("提示").setMessage("确定要删除该产品?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (null!=onOkListener){
                            onOkListener.onClick(null);
                        }
                        loadData();
                    }
                }).setNegativeButton("取消",null)
                .show();
    }
}
